package cn.demengsite.service.impl;

import cn.demengsite.dao.MemberDAO;
import cn.demengsite.dao.OrderDAO;
import cn.demengsite.dao.ProductDAO;
import cn.demengsite.model.BaseInfo;
import cn.demengsite.model.DTO.CashDTO;
import cn.demengsite.model.Order;
import cn.demengsite.model.Product;
import cn.demengsite.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDAO orderDAO;

    @Autowired
    private MemberDAO memberDAO;

    @Autowired
    private ProductDAO productDAO;

    @Override
    @Transactional
    public BaseInfo submitCash(CashDTO cashDTO) {
        Order order = cashDTO.getOrder();

        if(order.getMemberId()!=0){
            //如果是本店会员
            if (order.getBalancePay().compareTo(0d)!=0) {
                //如果会员有用余额支付，则更新会员表
                memberDAO.memberRecharge(order.getBalancePay()*-1,order.getMemberId());
            }

            if(order.getScorePay().compareTo(0d)!=0){
                //如果有积分支付，则更新会员表的积分值
                Double scoreTotal = order.getScorePay()*33.3;
                memberDAO.memberGainScores(scoreTotal*-1,order.getMemberId());
            }

            //增加会员积分
            memberDAO.memberGainScores(order.getTotalPrice(),order.getMemberId());


        }

        //新建订单
        orderDAO.insertNewOrder(order);
        for (Product product : cashDTO.getProducts()) {
            if(product.getBarCode().length()==10){
                //自己编的条码，存入到另外一个表中
                product.setSaleType(3);
            }
            orderDAO.insertOrderProduct(order.getOrderId(),
                    product.getBarCode(),
                    product.getProductNum(),
                    product.getDiscount(),
                    product.getSaleType(),
                    product.getSalePrice());
            productDAO.updateProductNum(product.getBarCode(),product.getProductNum()*-1);
        }



        return new BaseInfo("0","成功插入",order);
    }
}
